<?php
/**
 * Object Relational Persistence Mapping Class for table: pay_payment_item
 *
 * @package	com.athena
 * @author	LHV
 */
class PayPaymentItem extends ORDataObject {

	/**#@+
	 * Fields of table: pay_payment_item mapped to class members
	 */
	var $pay_payment_item_id   = '';
	var $pay_payment_id        = '';
	var $service_name          = '';
	var $service_id            = '';
	var $unit                  = '';
	var $quantity              = '';
	var $unit_price            = '';
	var $original_price        = '';
	var $insurance_price       = '';
	var $discount              = '';
	var $patient_price         = '';
	var $enum_item_type        = '';
	var $change_price_note     = '';
	var $doctor_id             = '';
	var $date                  = '';
	var $real_payment          = '';
	var $collected             = '';
	/**#@-*/
	
	const COLLECTED  =   1;
	const CREDIT_ACCOUNT_ID   = -1;
    const CREDIT_ACCOUNT_NAME = "Credit account";
	/**
	 * DB Table
	 */
	var $_table = 'pay_payment_item';

	/**
	 * Primary Key
	 */
	var $_key = 'pay_payment_item_id';

	/**
	 * Internal Name
	 */
	var $_internalName = 'PayPaymentItem';

	/**
	 * Handle instantiation
	 */
	function PayPaymentItem() {
		parent::ORDataObject();
	}

    /**
     * Set data to the object from data of a BillableItem object
     *
     * @param BillableItem $objBillable
     */
	public function setDataFromBillableItem($objBillable) {
        $this->service_id   =   $objBillable->getServiceId();
        $this->service_name =   $objBillable->getServiceName();
        $this->unit         =   $objBillable->getUnit();
        $this->quantity     =   $objBillable->getQuantity();
        $this->unit_price   =   $objBillable->getOriginalUnitPrice();
        $this->original_price   =   $objBillable->getOriginalPrice();
        $this->insurance_price  =   $objBillable->getInsurancePrice();
        $this->discount         =   $objBillable->getDiscount();
        $this->patient_price    =   $objBillable->getPatientPrice();
        $this->enum_item_type   =   $objBillable->getType();
        $this->change_price_note    =   $objBillable->getChangePriceNote();
    }

    public function setPaymentId($paymentId) {
    	$this->pay_payment_id  =   $paymentId;
    }

    public static function getPaymentItemsByTicket($ticketId, $itemType = false, $queueOrder = true) {
    	$format    =   L10nHelper::getSqlDateFormat();
    	if ($queueOrder) {
    		$order    =   'DESC';
    	}
    	else {
    		$order    =   'ASC';
    	}
        $sql   =   array(
           'cols'  =>  "pay_payment_item_id, DATE_FORMAT(ppi.date, '$format') as date , ppi.date as original_date,
                ppi.service_id, ppi.service_name, s.code service_code, unit, ppi.quantity,
                ppi.unit_price, ppi.original_price, ppi.insurance_price, ppi.patient_price,
                ppi.enum_item_type, ppi.doctor_id, e.name doctor_name, ppi.collected",
           'from'  =>  "pay_payment_item ppi
                        INNER JOIN pay_payment pp ON (pp.pay_payment_id = ppi.pay_payment_id)
                        LEFT JOIN employee e ON (ppi.doctor_id = e.person_id)
                        LEFT JOIN service s ON (s.service_id = ppi.service_id)",
           'where' =>  "ticket_id='$ticketId'",
           'orderby'   =>  "ppi.pay_payment_item_id $order, ppi.date DESC"
        );
        if ($itemType !== false) {
            if (is_numeric($itemType)) {
        	   $sql['where']   .=  " AND enum_item_type = '$itemType'";
            }
            elseif (is_array($itemType) && count($itemType) > 0) {
                $itemType   =   implode(",", $itemType);
            	$sql['where']   .=  " AND enum_item_type IN ($itemType)";
            }
        }

        $ds    =   new Datasource_sql();
        $db    =   Celini::dbInstance();
        $ds->setup($db, $sql);
        $res    = $ds->toArray();
        if (count($res) > 0) {
            $serviceTypeList    =   Utils::getEnumArrayKey(EnumerationConstant::PAYMENT_ITEM_TYPE);
            foreach ($res as &$item) {
            	$item['item_type_text']                =   $serviceTypeList[$item['enum_item_type']];
            	$item['unit_price_formatted']          =   L10nHelper::renderNumber($item['unit_price']);
            	$item['original_price_formatted']      =   L10nHelper::renderNumber($item['original_price']);
            	$item['insurance_price_formatted']     =   L10nHelper::renderNumber($item['insurance_price']);
            	$item['patient_price_formatted']       =   L10nHelper::renderNumber($item['patient_price']);
            }
        }
        return $res;
    }

    public function setData($paymentId, $serviceId, $serviceName, $serviceType, $unit,
    		$quantity, $unitPrice, $orgPrice, $insPrice, $discount,
    		$patPrice, $doctorId, $date, $realPayment = 0) {
	    $data	=	array(
		    'pay_payment_id'	=>	$paymentId,
			'service_id'		=>	$serviceId,
			'service_name'		=>	$serviceName,
			'enum_item_type'	=>	$serviceType,
			'unit'				=>	$unit,
			'quantity'			=>	$quantity,
			'unit_price'		=>	$unitPrice,
			'original_price'	=>	$orgPrice,
			'insurance_price'	=>	$insPrice,
			'patient_price'		=>	$patPrice,
			'doctor_id'			=>	$doctorId,
			'date'				=>	$date,
			'real_payment'		=>	$realPayment
	    );
	    $this->populateArray($data);
    }

    public function deletePaymentItem($itemId) {
    	$sql	=	"DELETE FROM $this->_table WHERE $this->_key = '$itemId'";
    	$res   =   $this->_execute($sql);
    	return $res;
    }

    public function updateRealPayment($itemId, $amount) {
        $db    =   Celini::dbInstance();
        $sql   =   "UPDATE pay_payment_item SET real_payment = real_payment + $amount WHERE pay_payment_item_id = '$itemId'";
        $res   =   $db->Execute($sql);
        return $res;
    }

    public function getRealPayment() {
    	return $this->real_payment;
    }

    public function setRealPayment($val) {
    	$this->real_payment    =   $val;
    }

    public function getPatientPrice() {
    	return $this->patient_price;
    }

    public static function getCreditAmount($paymentId) {
        $sql    =   "SELECT real_payment FROM pay_payment_item WHERE pay_payment_id = '$paymentId' AND service_id = -1";
        $db     =   Celini::dbInstance();
        $res    =   $db->Execute($sql);
        if ($res && !$res->EOF) {
        	return $res->fields['real_payment'];
        }
        return 0;
    }

    public function checkItemsNotFullPaid($paymentId) {
    	$sql	=	"SELECT $this->_key FROM $this->_table WHERE (patient_price > real_payment) " .
    			" AND pay_payment_id = '$paymentId' AND service_id != " . PayPaymentItem::CREDIT_ACCOUNT_ID;
    	$res   =   $this->_execute($sql);
    	if ($res && !$res->EOF) {
	    	return true;
    	}
    	return false;

    }

    /**
     * Check if a ticket having billable items or not
     *
     * @param int $ticketId Ticket Id
     * @return bool Boolean result
     */
    public function checkTicketHavingBilableItem($ticketId) {
        $sql    =   "SELECT $this->_key FROM $this->_table t
                    INNER JOIN pay_payment pp ON (t.pay_payment_id = pp.pay_payment_id)
                    WHERE pp.ticket_id = '$ticketId' AND t.service_id!=" . self::CREDIT_ACCOUNT_ID;
        $res   =   $this->_execute($sql);
        if ($res && !$res->EOF) {
            return true;
        }
        return false;
    }

    public function getCreditAccountItem($paymentId) {
    	$sql   =   "SELECT $this->_key FROM $this->_table WHERE pay_payment_id = '$paymentId' AND service_id = " . PayPaymentItem::CREDIT_ACCOUNT_ID;
        $res   =    $this->_execute($sql);
        $obj   = Celini::newORDO('PayPaymentItem', $res->fields[$this->_key]);
        return $obj;
    }

    public function createCreditAccountItem($paymentId) {
    	$objPayItem =   Celini::newORDO('PayPaymentItem');
    	$data   =   array(
                'pay_payment_id'    =>  $paymentId,
                'service_id'        =>  PayPaymentItem::CREDIT_ACCOUNT_ID,
                'service_name'      =>  L10nHelper::_(PayPaymentItem::CREDIT_ACCOUNT_NAME),
                'doctor_id'         =>  -1,
    	        'enum_item_type'    =>  -1,
                'date'              =>  date('Y-m-d')
    	);
    	$objPayItem->populateArray($data);
    	$res   =   $objPayItem->persist();
    	return $res;
    }
    
    public static function updateItemStatus($paymentId, $status) {
        $sql    =   "UPDATE pay_payment_item ppi SET ppi.collected='$status' WHERE ppi.pay_payment_id = '$paymentId'";
        $db     =   Celini::dbInstance();
        $db->Execute($sql);
    }
}
?>
